package bookstudytest.annotation;



import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;


/**
 * @author :  fcx
 * @date : Create in 2017/10/20 0020 上午 8:52
 * @description :
 */
@TestAnnotation( value = "ss")
public class IndexController {
    @TestAnnotation("parameter")
    private String par;

    @TestAnnotation("method")
    /**
     * 得到类对应的注解对象
     */
    public void getClassAnnotation() {
        Class aClass = IndexController.class;
        if (aClass.isAnnotationPresent(TestAnnotation.class)) {
            //
//            Annotation annotation = aClass.getAnnotation(RestController.class);
//            System.out.println(annotation.toString());
            // 取得一个类上的所有注解
            Annotation[] annotations = aClass.getAnnotations();
            for (Annotation annotation : annotations) {
                if (annotation != null) {
                    if (annotation instanceof TestAnnotation) {
                        TestAnnotation requestMapping = (TestAnnotation) annotation;
                        System.out.println(requestMapping.value());
                    }
                }
            }
        }
    }

    //得到变量的注解对象
    public void getFieldAnnotation() {

        try {
            Field par = IndexController.class.getDeclaredField("par");
            TestAnnotation annotation = par.getAnnotation(TestAnnotation.class);
            System.out.println(annotation.value());
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

    }

    //得到方法对应的注解对象
    public void getMethodAnnotation() {
        Method[] declaredMethods = IndexController.class.getDeclaredMethods();
//        for (Method declaredMethod : declaredMethods) {
//            System.out.println(declaredMethod.getModifiers());
//            System.out.println(declaredMethod.getReturnType());
//            Class<?>[] parameterTypes = declaredMethod.getParameterTypes();
//            for (Class<?> parameterType : parameterTypes) {
//                System.out.println(parameterType.toString());
//            }
//        }
        try {
            Method method = IndexController.class.getDeclaredMethod("index");
            TestAnnotation annotation = method.getAnnotation(TestAnnotation.class);
            String value = annotation.value();
//            for (String s : value) {
//                System.out.println(s);
//            }
            System.out.println(value);

        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new IndexController().getMethodAnnotation();
    }
}
